import { useI18n } from "vue-i18n";

const nTimes = (char, count) => {
  let str = '';
  for (let i = 0; i < count; i++) {
    str += char;
  }
  return str;
}

const fillZeroStart = (length, string) => {
  if (typeof string != 'string') string = String(string);
  return string.length >= length ? string : `${nTimes('0', length - string.length)}${string}`;
}


const getMonthWeek = (date) => {
  const w = date.getDay()
  const d = date.getDate()
  return Math.ceil(
    (d + 6 - w) / 7
  )
}

export default function useDateToString(date: Date) {
const { t } = useI18n();

  const now = new Date();
  const nowYear = now.getFullYear();
  const nowMonth = now.getMonth() + 1;
  const nowWeekOfMonth = getMonthWeek(now);
  const nowDay = now.getDate();
  const nowDayOfWeek = now.getDay();

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const weekOfMonth = getMonthWeek(date);
  const day = date.getDate();
  const dayOfWeek = date.getDay();



  const dateStrings = [];

  if (nowYear == year && nowMonth == month && day <= nowDay) {
    // 如果时间和当前在同一年同一月，并且日期不在当前日期之后
    if(nowDay == day) {
      // 如果是同一天，返回 类似 今天 hh:mm 的形式
      dateStrings.push(t('date.today'));
    } else if(day == nowDay - 1) {
      // 如果是前一天，返回 类似 昨天 hh:mm 的形式
      dateStrings.push(t('date.yesterday'));
    } else if(day == nowDay - 2) {
      // 如果是前两天，返回 类似 前天 hh:mm 的形式
      dateStrings.push(t('date.twodaysago'));
    } else if(nowWeekOfMonth == weekOfMonth) {
      // 否则，和当前时间是同一周，返回 类似 星期日 hh:mm 的形式
      dateStrings.push(t(`date.dayOfWeek.${dayOfWeek}`));
    } else {
      // 否则，和当前时间只是同年同月，返回 类似 19日 hh:mm 的形式
      dateStrings.push(`${day}${t('date.daySplitor')}`);
    }
  } else if (nowYear == year && day <= nowDay) {
    // 如果仅仅同年（说明不同月）并且日期不在当前日期之后
    dateStrings.push(`${month}${t('date.monthSplitor')}${day}${t('date.daySplitor')}`);
  } else {
    // 到了现在，有两种情况，年份不同或者是日期在当前日期之后，这两种情况，我们都采用最全的格式
    dateStrings.push(`${year}${t('date.yearSplitor')}${month}${t('date.monthSplitor')}${day}${t('date.daySplitor')}`);
  }

  const hhmmss = `${date.getHours()}:${fillZeroStart(2, date.getMinutes())}:${fillZeroStart(2, date.getSeconds())}`
  dateStrings.push(hhmmss);
  const dateString = dateStrings.join(' ');

  return dateString;
}